// utils/token-debug.js
// Token调试工具 - 专门用于诊断Token获取问题

class TokenDebugger {
  constructor() {
    this.config = {
      username: 'ilieyun',
      password: 'Lieyun@2090',
      domain: 'ilieyun',
      project: 'cn-north-4'
    }
  }

  // 调试Token获取过程
  async debugTokenFetch() {
    console.log('=== Token获取调试开始 ===')
    
    try {
      const tokenUrl = 'https://iam.cn-north-4.myhuaweicloud.com/v3/auth/tokens'
      
      const tokenRequest = {
        auth: {
          identity: {
            methods: ['password'],
            password: {
              user: {
                name: this.config.username,
                password: this.config.password,
                domain: {
                  name: this.config.domain
                }
              }
            }
          },
          scope: {
            project: {
              name: this.config.project
            }
          }
        }
      }

      console.log('1. 发送Token请求...')
      console.log('请求URL:', tokenUrl)
      console.log('请求体:', JSON.stringify(tokenRequest, null, 2))

      const response = await wx.request({
        url: tokenUrl,
        method: 'POST',
        data: tokenRequest,
        header: {
          'Content-Type': 'application/json'
        },
        timeout: 15000
      })

      console.log('2. 收到响应...')
      console.log('响应状态码:', response.statusCode)
      console.log('响应状态:', response.status)
      console.log('响应数据:', response.data)

      console.log('3. 检查响应头...')
      if (response.header) {
        console.log('响应头对象类型:', typeof response.header)
        console.log('响应头是否为数组:', Array.isArray(response.header))
        console.log('响应头键名列表:', Object.keys(response.header))
        
        // 打印所有响应头
        console.log('所有响应头内容:')
        console.log('响应头类型:', typeof response.header)
        console.log('响应头是否为Proxy:', response.header && response.header.constructor && response.header.constructor.name === 'Proxy')
        
        // 尝试不同的方式访问响应头
        const headerKeys = Object.keys(response.header)
        console.log('响应头键名列表:', headerKeys)
        
        headerKeys.forEach(key => {
          try {
            const value = response.header[key]
            console.log(`  ${key}: ${value}`)
          } catch (error) {
            console.log(`  ${key}: [无法访问]`)
          }
        })
        
        // 特别查找Token相关的头
        console.log('4. 查找Token相关响应头...')
        const tokenKeys = [
          'X-Subject-Token',
          'x-subject-token',
          'X-SUBJECT-TOKEN',
          'x_subject_token',
          'subject-token',
          'Subject-Token'
        ]
        
        let foundToken = null
        let foundKey = null
        
        for (const key of tokenKeys) {
          if (response.header[key]) {
            foundToken = response.header[key]
            foundKey = key
            console.log(`✅ 找到Token! 键名: ${key}`)
            console.log(`Token值: ${foundToken.substring(0, 20)}...`)
            break
          }
        }
        
        if (!foundToken) {
          console.log('❌ 未找到Token，检查所有可能的键名...')
          
          // 查找包含token的键名
          const allKeys = Object.keys(response.header)
          const tokenRelatedKeys = allKeys.filter(key => 
            key.toLowerCase().includes('token') || 
            key.toLowerCase().includes('subject')
          )
          
          console.log('包含token或subject的键名:', tokenRelatedKeys)
          
          for (const key of tokenRelatedKeys) {
            console.log(`  ${key}: ${response.header[key]}`)
          }
        }
        
        return {
          success: !!foundToken,
          token: foundToken,
          tokenKey: foundKey,
          statusCode: response.statusCode,
          headers: response.header,
          data: response.data
        }
      } else {
        console.log('❌ 响应头为空或未定义')
        return {
          success: false,
          error: '响应头为空或未定义',
          statusCode: response.statusCode,
          data: response.data
        }
      }
    } catch (error) {
      console.log('❌ Token获取异常:', error)
      return {
        success: false,
        error: error.message,
        stack: error.stack
      }
    }
  }

  // 运行完整调试
  async runFullDebug() {
    console.log('=== Token完整调试 ===')
    
    const result = await this.debugTokenFetch()
    
    console.log('=== 调试结果 ===')
    console.log('成功:', result.success)
    
    if (result.success) {
      console.log('Token获取成功!')
      console.log('Token键名:', result.tokenKey)
      console.log('Token值:', result.token.substring(0, 20) + '...')
      return result.token
    } else {
      console.log('Token获取失败!')
      console.log('错误信息:', result.error)
      throw new Error(`Token获取失败: ${result.error}`)
    }
  }
}

module.exports = new TokenDebugger()
